package point

import (
	"fmt"
	"os/exec"
	"regexp"
	"strings"
)

type WifiXApClosePoint struct {
	index int
}

func NewWifiXApClosePoint() *WifiXApClosePoint { return &WifiXApClosePoint{} }

func (s *WifiXApClosePoint) Get() any {
	return nil
}

func (m *WifiXApClosePoint) Set(val ...any) bool {

	getConnectionUuid := func(iface string) string {
		cmd := exec.Command("nmcli", "connection")
		output, err := cmd.Output()
		if err != nil {
			return ""
		}

		lines := strings.Split(string(output), "\n")

		pattern := `\s*(.*?)\s+\s+(.*?)\s+\s+(.*?)\s+\s+(.*?)\s*$`
		re := regexp.MustCompile(pattern)

		for _, line := range lines {
			if line == "" {
				continue
			}
			parts := re.FindStringSubmatch(line)
			if len(parts) != 5 {
				continue
			}
			// name, uuid, typ, device := parts[1], parts[2], parts[3], parts[4]
			// fmt.Printf("NAME: %s, UUID: %s, TYPE: %s, DEVICE: %s\n", name, uuid, typ, device)

			if parts[4] == iface {
				return parts[2]
			}
		}

		return ""
	}

	connect := getConnectionUuid("wlan0")
	if connect == "" {
		wifixApState = "close"
		return true
	}

	err := exec.Command("nmcli", "connection", "down", connect).Run()
	if err != nil {
		fmt.Println("close ap failed, err --> ", err)
		return false
	}

	wifixApState = "close"
	return true
}

func (m *WifiXApClosePoint) SetRoute(str string) PointInterface {
	m.index = int(str[len("wan")]) - '0'
	return m
}
